'use strict';

/**
 * decodeURI 将URI（统一资源标识符）解码，如其中的URL统一资源定位符
 */
var Cookie = {
	/**
	 * @Description 获取cookie
	 * @param key
	 */
	get: function get(key) {
		function process(key) {
			if (!key) {
				return key;
			}
			for (; key !== decodeURI(key);) {
				key = decodeURI(key);
			}
			var encode = ['<', '>', "'", '"', '%3c', '%3e', '%27', '%22', '%253c', '%253e', '%2527', '%2522'];
			var e16 = ['&#x3c;', '&#x3e;', '&#x27;', '&#x22;', '%26%23x3c%3B', '%26%23x3e%3B', '%26%23x27%3B', '%26%23x22%3B', '%2526%2523x3c%253B', '%2526%2523x3e%253B', '%2526%2523x27%253B', '%2526%2523x22%253B'];
			for (var i = 0; i < encode.length; i++) {
				key = key.replace(new RegExp(encode[i], 'gi'), e16[i]);
			}
			return key;
		}
		// 正则匹配key返回数组赋值给res
		var reg = RegExp('(^|;\\s*)' + key + '=([^;]*)(;|$)');
		var res = void 0;
		var param = (res = document.cookie.match(reg)) ? decodeURI(res[2]) : '';
		return process(param);
	},

	/**
	 * @Description   添加cookie四属性
	 * @param key     cookie名
	 * @param value   cookie值
	 * @param domain  domain值
	 * @param path    path值
	 * @param expires 过期时间(小时)
	 */
	set: function set(key, value, domain, path, expires) {
		var time = new Date();
		if (expires) {
			time.setTime(time.getTime() + 36e5 * expires);
			// t + '=' + e + '; expires=' + p.toGMTString() + '; path=' + (n || '/') + '; ' + (i ? 'domain=' + i + ';' : ''))
			document.cookie = key + '=' + value + '; expires=' + time.toGMTString() + '; path=' + (path || '/') + ';' + (domain ? ' domain=' + domain + ';' : '');
		} else {
			// t + '=' + e + '; path=' + (n || '/') + '; ' + (i ? 'domain=' + i + ';' : '')
			document.cookie = key + '=' + value + '; path=' + (path || '/') + ';' + (domain ? ' domain=' + domain + ';' : '');
		}
	},

	/**
	 * @Description  删除cookie
	 * @param key
	 * @param domain
	 * @param path
	 */
	del: function del(key, domain, path) {
		// t + '=; expires=Mon, 26 Jul 1997 05:00:00 GMT; path=' + (i || '/') + '; ' + (e ? 'domain=' + e + ';' : '')
		document.cookie = key + '=; expires=Mon, 26 Jul 1997 05:00:00 GMT; path=' + (path || '/') + ';' + (domain ? ' domain=' + domain : '');
	},

	/**
	 * 转换成对象序列
	 * @param callback
	 */
	toObj: function toObj(callback) {
		var temp = {};
		var val = document.cookie.match(/(^|;\s*)\S+(\w+)/g);
		val = val.map(function (e) {
			return e.indexOf('; ') !== -1 ? e.substring(e.indexOf('; ') + 2) : e;
		});
		val.forEach(function (e) {
			return temp[e.split('=')[0]] = e.split('=')[1];
		});
		return temp;
	},

	/**
	 * 清空cookie
	 * 需要遍历设置为null 不能直接复制为null
	 */
	clear: function clear() {
		var v = this.toObj();
		for (var k in v) {
			if (v.hasOwnProperty(k)) {
				this.del(k);
			}
		}
	}
};